介紹
將訊息從發送方與接收方間解耦。
以下範例取自Game Programming Patterns一書。
C++範例片段
// 播放音效的資訊
struct PlayMessage
{
SoundId id;
int volume;
};
class Audio
{
public:
static void Init()
{
m_head = 0;
m_tail = 0;
}
// 將要播放的音效資訊加入列隊
void Audio::playSound(SoundId id, int volume)
{
assert((m_tail + 1) % MAX_PENDING != m_head);
// Add to the end of the list.
m_pending[m_tail].id = id;
m_pending[m_tail].volume = volume;
m_tail = (m_tail + 1) % MAX_PENDING; // ring buffer
}
// 播放列隊中的音效
void Audio::update()
{
// If there are no pending requests, do nothing.
if (m_head == m_tail)
return;
ResourceId resource = loadSound(m_pending[m_head].id);
int channel = findOpenChannel();
if (channel == -1)
return;
startSound(resource, channel, m_pending[m_head].volume);
m_head = (m_head + 1) % MAX_PENDING; // ring buffer
}
private:
static const int MAX_PENDING = 16;
static PlayMessage m_pending[MAX_PENDING];
static int m_head;
static int m_tail;
};
Ref:
https://gameprogrammingpatterns.com/event-queue.html